package com.itlong.cloud.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.itlong.cloud.POJO.DTO.operate.OperateLicenseDTO;
import com.itlong.cloud.POJO.DTO.smartcard.SmartCardSyncMessageDTO;
import com.itlong.cloud.POJO.VO.MessageVO;
import com.itlong.cloud.POJO.VO.property.CloudElevatorVO;
import com.itlong.cloud.POJO.VO.property.CloudTalkIotInfoVO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.annotation.LoggerInfo;
import com.itlong.cloud.constants.LogDescConstant;
import com.itlong.cloud.constants.RedisConstant;
import com.itlong.cloud.enumerate.SystemTypeEnum;
import com.itlong.cloud.enumerate.ecode.BaseErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.SmartCardErrorCodeEnum;
import com.itlong.cloud.equip.property.IPropertyEquipServiceClient;
import com.itlong.cloud.project.operate.IOperateProjectServiceClient;
import com.itlong.cloud.service.RedisService;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.utils.encrypt.Md5EncryptUtil;
import com.itlong.cloud.utils.encrypt.UserTokenUtil;
import com.itlong.cloud.utils.node.JsonUtil;
import com.itlong.cloud.utils.words.StringHandlerUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;


/**
* <desc>
*     一卡通登录控制器.
* </desc>
*
* @createDate 2017-12-15
*/
@RestController
@RequestMapping("/smartCard/syncdata/")
@RefreshScope
public class SmardCardLoginController {


    @Autowired
    RedisService redisService;

    @Autowired
    IOperateProjectServiceClient iOperateProjectServiceClient;

    @Autowired
    IPropertyEquipServiceClient iPropertyEquipServiceClient;


    @Value("${" + PlatformConstants.SMART_CARD_TOKEN_KEY + "}")
    String userTokenKey;

    @Value("${" + PlatformConstants.IOT_SMART_CARD_PRODUCT_KEY + "}")
    private  String smartCardIotProductKey; //一卡通产品KEY

    /**
     * <desc>
     *      一卡通登录。
     * <desc/>
     *
     * @param  projectId 项目编号
     * @param  factor  密钥因子(32位GUID字符串 eg:afc3a088cd344dcf96d3ac984757fab2)
     * @param  key  登录Key,密钥因子factor加上旺龙标识itlong，组成新的字符串N（eg: afc3a088cd344dcf96d3ac984757fab2itlong），
     *              对N进行MD5加密后得到登录Key：d2e44c4ff039eb4e87e7ff8281c356eb
     * @return
     * @author LouisLewis
     * @createDate 2017-12-15
     */
    @LoggerInfo(operateDesc = LogDescConstant.SMART_CARD_SYNC_DATA_LOGIN)
    @ResponseBody
    @RequestMapping(path = "cloudServer/login",method = RequestMethod.POST)
    public MessageVO login(@RequestParam("projectId") String projectId,@RequestParam("factor") String factor,
                          @RequestParam("key") String key){
        MessageVO messageVO;

        try {
            //判断账户和密码
            if(StringUtils.isBlank(projectId) || StringUtils.isBlank(factor)||(StringUtils.isBlank(key))){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }

            if (!checkKeyValid(factor,key)){
               return new MessageVO(SmartCardErrorCodeEnum.LOGIN_PARAM_ERR.getErrorCode());
            }

            if (iOperateProjectServiceClient.checkProjectExist(projectId) <= 0){
                return new MessageVO(SmartCardErrorCodeEnum.PROJECT_NOT_EXISTS_ERR.getErrorCode());
            }

            String token = UserTokenUtil.tokenEncrypt(
                    projectId,userTokenKey, SystemTypeEnum.SMART_CARD.getType());

            //将登录Token存入缓存
            redisService.set(RedisConstant.SMART_CARD_SYNC_DATA_LOGIN_KEY +  projectId,
                    RedisConstant.SMART_CARD_SYNC_DATA_LOGIN_TIME,
                    token);
            iPropertyEquipServiceClient.checkSmartCardIot(projectId);//注册一卡通iot

            SmartCardSyncMessageDTO  smartCardSyncMessageDTO = new SmartCardSyncMessageDTO();
            smartCardSyncMessageDTO.setProjectId(projectId);
            smartCardSyncMessageDTO.setInfo(token);

//            SmartCardSyncDataVO smartCardSyncDataVO = new SmartCardSyncDataVO(projectId,"",token);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),smartCardSyncMessageDTO);
        }catch (Exception e){
            throw new DataAccessException("【一卡通_数据同步_登录】一卡通数据同步登录失败", e);
        }

    }
    /**
     * <desc>
     *      一卡通获取iot信息。
     * <desc/>
     *
     * @param  projectId 项目编号
     * @return
     * @author Qiang.S
     * @createDate 2019-07-25
     */
    @ResponseBody
    @RequestMapping(path = "cloudServer/getSmartCardIotInfo",method = RequestMethod.POST)
    public MessageVO getSmartCardIotInfo(@RequestBody String projectId) {
        try {
            projectId = JsonUtil.toObject(projectId,String.class);
            //判断项目编号
            if(StringUtils.isBlank(projectId)){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            CloudElevatorVO vo = iPropertyEquipServiceClient.checkSmartCardIot(projectId);
            Map<String,Object> result = new HashMap<>();
            if (vo != null) {
                result.put("iotProductKey",smartCardIotProductKey);
                result.put("iotDeviceSecret",vo.getIotDeviceSecret());
            }
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), result);
        } catch (Exception e) {
            throw new DataAccessException("【一卡通_数据同步_获取iot信息】一卡通获取iot信息失败", e);
        }
    }


    /**
    * <desc>
    *     检查登录认证参数是否合法.
    * </desc>
    *
    * @param  factor 密钥因子(32位GUID字符串 eg:afc3a088cd344dcf96d3ac984757fab2)
    * @param  key 登录Key,密钥因子factor加上旺龙标识itlong，组成新的字符串N（eg: afc3a088cd344dcf96d3ac984757fab2itlong），
     *              对N进行MD5加密后得到登录Key：d2e44c4ff039eb4e87e7ff8281c356eb
    * @return 是否合法
    * @author LewisLouis
    * @createDate 2017-12-15
    */
    private boolean checkKeyValid(String factor,String key){
        String ITL_FLAG = "itlong";
        String encodeData =  Md5EncryptUtil.md5(String.format("%s%s",factor,ITL_FLAG));
        return StringHandlerUtil.compareStrIgnoreCaseWithOutEmpty(key,encodeData);
    }

    /**
     * <desc>
     *      一卡通登录获取证书信息
     * </desc>
     *
     * @param json 证书信息查询参数DTO
     * @return
     * @Author Zhu.yj
     * @createDate  2020/9/24
     */
    @RequestMapping(value = "/certificate/getCertificate", method = RequestMethod.POST)
    public MessageVO getCertificate(@RequestBody String json){
        try{
            OperateLicenseDTO operateLicenseDTO = JsonUtil.toObject(json, OperateLicenseDTO.class);
            if (operateLicenseDTO == null || StringUtils.isBlank(operateLicenseDTO.getProjectId())){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            Map<String, Object> resultMap = iOperateProjectServiceClient.getCertificate(operateLicenseDTO);
            if (resultMap == null){
                return new MessageVO(SmartCardErrorCodeEnum.PROJECT_NONE_CERTIFICATE.getErrorCode());
            }
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), resultMap);
        }catch (Exception e){
            throw new DataAccessException("【一卡通_数据同步_获取证书信息】登录获取证书失败", e);
        }
    }
}
